<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/ldx.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/ldx.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/ldx.png?v=5.1.4">


  <link rel="mask-icon" href="/images/ldx1.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Oracle,SQL优化," />




  


  <link rel="alternate" href="/atom.xml" title="Ysshao'Blog" type="application/atom+xml" />






<meta name="description" content="SQL优化思路-Oracle篇为什么要重点提及SQL优化？ 关于SQL优化的教程很多，也是结合了各种资料以及书籍进行整理。下面给大家分享一下。 作为程序员经常和数据库打交道的时候还是非常频繁的，掌握住一些Sql的优化技巧还是非常有必要的。下面列出一些常用的SQl优化技巧。 在工作中发现在数据库方面的一些现象：  开发人员将数据库视为“黑盒子”，开发人员不关心，不重视SQL的执行过程，只关注具体的应">
<meta property="og:type" content="article">
<meta property="og:title" content="你真的了解“SQL”吗？">
<meta property="og:url" content="https://ysshao.cn/Oracle/SQL-Oracle/index.html">
<meta property="og:site_name" content="Ysshao&#39;Blog">
<meta property="og:description" content="SQL优化思路-Oracle篇为什么要重点提及SQL优化？ 关于SQL优化的教程很多，也是结合了各种资料以及书籍进行整理。下面给大家分享一下。 作为程序员经常和数据库打交道的时候还是非常频繁的，掌握住一些Sql的优化技巧还是非常有必要的。下面列出一些常用的SQl优化技巧。 在工作中发现在数据库方面的一些现象：  开发人员将数据库视为“黑盒子”，开发人员不关心，不重视SQL的执行过程，只关注具体的应">
<meta property="og:image" content="https://ysshao.cn/Oracle/SQL-Oracle/sqlzxgc.png">
<meta property="og:image" content="https://ysshao.cn/Oracle/SQL-Oracle/sqlcb.png">
<meta property="og:image" content="https://ysshao.cn/Oracle/SQL-Oracle/sqlyh.png">
<meta property="og:image" content="https://ysshao.cn/Oracle/SQL-Oracle/oracle_yh.png">
<meta property="article:published_time" content="2020-04-11T15:50:30.000Z">
<meta property="article:modified_time" content="2020-06-06T07:07:01.903Z">
<meta property="article:author" content="ysshao">
<meta property="article:tag" content="Oracle">
<meta property="article:tag" content="SQL优化">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://ysshao.cn/Oracle/SQL-Oracle/sqlzxgc.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://ysshao.cn/Oracle/SQL-Oracle/"/>





  <title>你真的了解“SQL”吗？ | Ysshao'Blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?50872c355dd0a87c31d032a47d741d41";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




<meta name="generator" content="Hexo 4.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a href="https://ysshao.cn/Notes/" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Ysshao'Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">人生太苦,多加点糖。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://ysshao.cn/Oracle/SQL-Oracle/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="ysshao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/allen.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Ysshao'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">你真的了解“SQL”吗？</h1>
        

        <div class="post-meta">
          <span class="post-time">
          
					    <i class="fa fa-thumb-tack"></i>
					    <font color="green">置顶</font>
					    <span class="post-meta-divider">|</span>
					
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-04-11T23:50:30+08:00">
                2020-04-11
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Oracle/" itemprop="url" rel="index">
                    <span itemprop="name">Oracle</span>
                  </a>
                </span>

                
                
              
            </span>
          

          

          
          
             <span id="/Oracle/SQL-Oracle/" class="leancloud_visitors" data-flag-title="你真的了解“SQL”吗？">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  9.2k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  34
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="SQL优化思路-Oracle篇"><a href="#SQL优化思路-Oracle篇" class="headerlink" title="SQL优化思路-Oracle篇"></a>SQL优化思路-Oracle篇</h1><p><strong>为什么要重点提及SQL优化？</strong></p>
<p>关于SQL优化的教程很多，也是结合了各种资料以及书籍进行整理。下面给大家分享一下。</p>
<p>作为程序员经常和数据库打交道的时候还是非常频繁的，掌握住一些Sql的优化技巧还是非常有必要的。下面列出一些常用的SQl优化技巧。</p>
<p><code>在工作中发现在数据库方面的一些现象</code>：</p>
<ol>
<li><p><strong>开发人员将数据库视为“黑盒子”</strong>，开发人员不关心，不重视SQL的执行过程，只关注具体的应用层体现。</p>
</li>
<li><p><strong>对SQL质量的重视程度不够</strong>,我们在日常项目中通常是不重视SQL的执行,没有经过大数量的反复推敲。</p>
<p>通常是直到项目上线，甚至到出现性能问题时，才会重点关注分析。或者是有DBA介人处理。这种救火模式，往往效果不好，即使有了解决方案，其代价、成本也必然是巨大的。</p>
</li>
<li><p><strong>开发人员想提高，但是无从下手</strong>。有部分开发人员意识到了SQL语句的重要性，但是无从下手。可能只是靠自我的日常积累。导致我们想提高缺困难重重！</p>
</li>
</ol>
<p><code>场景误区</code>：</p>
<ol>
<li><p><strong>关系数据库已死</strong>，近些年来，随着NoSQL的发展盛兴和推广，有一种观点就是关系数据库必将死亡，NoSQL将取而代之！随之而来的就是SQL优化没有必要，NoSQL作为一种新兴的技术，的确有其鲜明的特点，也适用于一些场合。但我们要看到，很多需要ACID的场景下，传统数据库仍然是不二选择，不可取代。</p>
</li>
<li><p><strong>SQL优化很简单</strong>,有些人认为，SQL优化很简单，部分人观点SQL优化不就是加几个索引嘛，有啥难的！</p>
<p>但其不是唯一的。且很多情况下，加了索引可能导致性能更差。在我们真实的项目中观察到单表存在10多个索引的情况。</p>
</li>
<li><p><strong>SQL优化只是DBA的事情</strong>,在我们的开发过程中，只关注自身的业务功能实现而忽略了相应的执行成本。</p>
<p>最终就导致上线后系统运行缓慢，代码质量不够。客户体验较差等问题。</p>
</li>
</ol>
<h2 id="SQL语句的执行顺序"><a href="#SQL语句的执行顺序" class="headerlink" title="SQL语句的执行顺序"></a>SQL语句的执行顺序</h2><blockquote>
<p><strong>SQL Select语句完整的执行顺序</strong></p>
<ol>
<li>from子句组装来自不同数据源的数据；</li>
<li>where子句基于指定的条件对记录行进行筛选；</li>
<li>group by子句将数据划分为多个分组；</li>
<li>使用聚集函数进行计算；</li>
<li>使用having子句筛选分组；</li>
<li>计算所有的表达式；</li>
<li>使用order by对结果集进行排序。</li>
<li>select 集合输出。</li>
</ol>
</blockquote>
<table>
<thead>
<tr>
<th>序号</th>
<th>语法顺序</th>
<th>加载顺序</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td>SELECT[DISTINCT]</td>
<td>FROM</td>
</tr>
<tr>
<td>2</td>
<td>FROM</td>
<td>WHERE</td>
</tr>
<tr>
<td>3</td>
<td>WHERE</td>
<td>GROUP BY</td>
</tr>
<tr>
<td>4</td>
<td>GROUP BY</td>
<td>HAVING</td>
</tr>
<tr>
<td>5</td>
<td>HAVING</td>
<td>SELECT</td>
</tr>
<tr>
<td>6</td>
<td>UNION</td>
<td>DISTINCT</td>
</tr>
<tr>
<td>7</td>
<td>ORDER BY</td>
<td>UNION</td>
</tr>
<tr>
<td>8</td>
<td></td>
<td>ORDER BY</td>
</tr>
</tbody></table>
<h2 id="理解SQL执行原理和过程"><a href="#理解SQL执行原理和过程" class="headerlink" title="理解SQL执行原理和过程"></a>理解SQL执行原理和过程</h2><ul>
<li><p><strong>客户端把语句发给服务器端执行</strong></p>
<p>​        当我们在客户端执行 select 语句时,客户端会把这条 SQL 语句发送给服务器端,让服务器端的进程来处理这语句。</p>
</li>
<li><p><strong>语句解析</strong></p>
<blockquote>
<ol>
<li>查询高速缓存(library cache)。服务器进程在接到客户端传送过来的 SQL 语句时,不会直接去数据库查询。而是会先在数据库的高速缓存中去查找,是否存在相同语句的执行计划。如果在数据高速缓存中,则服务器进程就会直接执行这个 SQL 语句,省去后续的工作。所以,采用高速数据缓存的话,可以提高 SQL 语句的查询效率。</li>
<li>语句合法性检查(data dict cache)。当在高速缓存中找不到对应的 SQL 语句时则服务器进程就会开始检查这条语句的合法性。这里主要是对 SQL 语句的语法进行检查,看看其是否合乎语法规则。如果服务器进程认为这条 SQL 语句不符合语法规则的时候,就会把这个错误信息,反馈给客户端。注意:此阶段不会对 SQL 语句中所包含的表名、列名等等进行 SQL 他只是语法。</li>
<li>语言含义检查(data dict cache)。若 SQL 语句符合语法上的定义的话,则服务器进程，接下去会对语句中的字段、表等内容进行检查。看看这些字段、表是否在数据库中。</li>
<li>获得对象解析锁(control structer)。当语法、语义都正确后,系统就会对我们需要查询的对象加锁。这主要是为了保障数据的一致性,防止我们在查询的过程中,其他用户对这个对象的结构发生改变。</li>
<li>数据访问权限的核对(data dict cache)。当语法、语义通过检查之后,客户端还不一定能够取得数据。服务器进程还会检查,你所连接的用户是否有这个数据访问的权限。</li>
<li><strong>确定最佳执行计划</strong> 。当语句与语法都没有问题,权限也匹配的话,服务器进程还是不会直接对数据库文件进行查询，服务器进程会根据一定的规则,对这条语句进行优化; 当服务器进程的优化器确定这条查询语句的最佳执行计划后,就会将这条 SQL 语句与执行计划保存到数据高速缓存。</li>
</ol>
</blockquote>
</li>
<li><p><strong>绑定变量</strong></p>
<p>如果SQL语句中使用了绑定变量，扫描绑定变量的声明，给绑定变量赋值，将变量值带入执行计划。若在解析的第一个步骤，SQL在高速缓冲中存在，则直接跳到该步骤。</p>
</li>
<li><p><strong>语句执行</strong></p>
<blockquote>
<p>语句解析只是对 SQL 语句的语法进行解析,以确保服务器能够知道这条语句到底表达的是什么意思。等到语句解析完成之后,数据库服务器进程才会真正的执行这条 SQL 语句。</p>
<p><strong>对于SELECT语句：</strong></p>
<ol>
<li><p>若被选择行所在的数据块已经被读取到数据缓冲区的话,则服务器进程会直接把这个数据传递给客户端,而不是从数据库文件中去查询数据。</p>
</li>
<li><p>若数据不在缓冲区中,则服务器进程将从数据库文件中查询相关数据,并把这些数据放入到数据缓冲区中(buffer cache)</p>
</li>
</ol>
<p><strong>对于DML语句（insert、update、delete）</strong></p>
<ol>
<li>检查所需的数据库是否已经被读取到缓冲区缓存中。如果已经存在缓冲区缓存，则直接执行步骤3；</li>
<li>若所需的数据库并不在缓冲区缓存中，则服务器将数据块从数据文件读取到缓冲区缓存中.</li>
<li>对想要修改的表取得的数据行锁定，之后对所需要修改的数据行取得独占锁；</li>
<li>将数据的Redo记录复制到redo log buffer；</li>
<li>产生数据修改的undo数据；</li>
<li>修改数据，其实是修改的缓存区中的数据（db buffer；）；</li>
<li>后台dbwr将修改写入数据文件；</li>
</ol>
</blockquote>
</li>
<li><p><strong>提取数据</strong></p>
<p>​        当语句执行完成之后,查询到的数据还是在服务器进程中,还没有被传送到客户端的用户进程。所以,在服务器端的进程中,有一个专门负责数据提取的一段代码。他的作用就是把查询到的数据结果返回给用户端进程,从而完成整个查询动作。</p>
<p>最终整体的SQL运行流程如下：</p>
<img src="/Oracle/SQL-Oracle/sqlzxgc.png" alt="SQL执行过程" style="zoom:50%;">

</li>
</ul>
<h2 id="如何写出高性能的SQL"><a href="#如何写出高性能的SQL" class="headerlink" title="如何写出高性能的SQL"></a>如何写出高性能的SQL</h2><p><strong>SQL语句的解析方式</strong></p>
<blockquote>
<p>根据前面我们讲到了高速缓存区，可以知道通过SQL文本计算的哈希值无法在缓存区找到，则开启硬解析的一个过程。优化器最终产生一个最优的执行计划。</p>
<p>总体分析：</p>
<ul>
<li>硬解析即整个<em>SQL</em>语句的执行需要完完全全的解析，生成执行计划。那么此过程就非常消耗CPU和内存资源。</li>
<li>软解析省略了以上过程。</li>
</ul>
<p>SQL语句的解析有软解析soft parse与硬解析hard parse，以下是5个步骤：</p>
<p>1：语法是否合法(sql写法)</p>
<p>2：语义是否合法(权限，对象是否存在)</p>
<p>3：检查该sql是否在共享池中存在</p>
<p>– 如果存在,直接跳过4和5,运行sql. 此时算soft parse</p>
<p>4：选择执行计划</p>
<p>5：产生执行计划</p>
</blockquote>
<p>后续我们重点关注SQL的语句解析和执行计划</p>
<h3 id="减少硬解析"><a href="#减少硬解析" class="headerlink" title="减少硬解析"></a>减少硬解析</h3><p>观察一下SQL的执行的执行过程</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> <span class="keyword">sysdate</span> <span class="keyword">from</span> dual; </span><br><span class="line"><span class="keyword">select</span> <span class="keyword">sysdate</span>  <span class="keyword">from</span> dual;</span><br><span class="line"><span class="keyword">Select</span> <span class="keyword">sysdate</span> <span class="keyword">From</span> Dual;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">*对于以上SQL,站在我们开发角度认为他们是相同，但是数据库优化器认为是不同的。</span></span><br><span class="line"><span class="comment">*查询v$sql试图观察实际情况</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">SELECT</span> SQL_TEXT,SQL_ID, FIRST_LOAD_TIME,EXECUTIONS <span class="keyword">FROM</span> V$<span class="keyword">SQL</span>  </span><br><span class="line"><span class="keyword">WHERE</span> SQL_TEXT <span class="keyword">LIKE</span> <span class="string">'% sysdate%'</span> <span class="keyword">ORDER</span> <span class="keyword">BY</span> FIRST_LOAD_TIME  <span class="keyword">DESC</span> ;</span><br></pre></td></tr></table></figure>

<p>通常我们可以使用一下这些方式排查硬解析</p>
<ul>
<li>排查硬解析的次数 查询某条SQL执行的次数</li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">Select</span>  SQL_TEXT <span class="keyword">as</span> <span class="keyword">SQL</span>文本,</span><br><span class="line">        EXECUTIONS <span class="keyword">as</span>  执行次数,</span><br><span class="line">        FIRST_LOAD_TIME <span class="keyword">as</span> 初次载入时间,</span><br><span class="line">        PARSE_CALLS <span class="keyword">as</span> 解析调用次数 ,</span><br><span class="line">        DISK_READS <span class="keyword">as</span> 读磁盘次数,</span><br><span class="line">        BUFFER_GETS <span class="keyword">as</span> 读缓存区次数 ,</span><br><span class="line">        OPTIMIZER_MODE <span class="keyword">as</span> <span class="keyword">SQL</span>语句的优化器模型 ,</span><br><span class="line">        CPU_TIME <span class="keyword">as</span> CPU使用时间单位毫秒</span><br><span class="line">         <span class="keyword">from</span> v$<span class="keyword">sql</span> <span class="keyword">where</span> sql_text <span class="keyword">like</span> <span class="string">'%hello sql%'</span>;</span><br></pre></td></tr></table></figure>

<ul>
<li>查看SQL只执行过一次的(分析相似的SQL找出硬解析SQL)</li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> sql_text <span class="keyword">from</span> v$<span class="keyword">sql</span> <span class="keyword">where</span> EXECUTIONS=<span class="number">1</span>;</span><br></pre></td></tr></table></figure>

<ul>
<li>查看系统中SQL解析的相关内容（parse count (total)=解析总次数、parse count (hard)=硬解析次数）    </li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">Select</span> <span class="keyword">name</span>,<span class="keyword">value</span> <span class="keyword">from</span> v$sysstat <span class="keyword">where</span> <span class="keyword">name</span> <span class="keyword">like</span> <span class="string">'parse%'</span>;</span><br></pre></td></tr></table></figure>

<ul>
<li>查询软解析率。如果软解析率低于30% ，则硬解析过多。 如果总解析量(parse count total)偏低，这项值可以被忽略</li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> <span class="number">1</span>-(a.value/b.value)/<span class="number">100</span> <span class="keyword">as</span> <span class="string">"软解析率%"</span></span><br><span class="line"><span class="keyword">from</span> v$sysstat a,v$sysstat b</span><br><span class="line"><span class="keyword">Where</span> a.name=<span class="string">'parse count (hard)'</span> <span class="keyword">and</span> b.name=<span class="string">'parse count (total)'</span>;</span><br></pre></td></tr></table></figure>
<h3 id="参数绑定"><a href="#参数绑定" class="headerlink" title="参数绑定"></a>参数绑定</h3><p>提高代码的可读性、提高代码安全性、防止SQL注入。</p>
<p><strong>存储过程绑定变量</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- Created on 2020/4/17 by ysshao</span></span><br><span class="line"><span class="keyword">declare</span> </span><br><span class="line"> v_userid <span class="built_in">varchar2</span>(<span class="number">20</span>):=<span class="string">'00010000130'</span>;</span><br><span class="line"> v_name  varchar2(100);</span><br><span class="line"><span class="keyword">begin</span></span><br><span class="line"> <span class="keyword">execute</span> <span class="keyword">immediate</span> <span class="string">'select username from user_info_temp where userid=:1 '</span> <span class="keyword">into</span> v_name  <span class="keyword">using</span> v_userid;</span><br><span class="line"> dbms_output.put_line(v_name);</span><br><span class="line"><span class="keyword">end</span>;</span><br></pre></td></tr></table></figure>

<p><strong>Java程序中绑定</strong></p>
<p>​    参数绑定+批量提交</p>
<h3 id="SQL语句不要太复杂"><a href="#SQL语句不要太复杂" class="headerlink" title="SQL语句不要太复杂"></a>SQL语句不要太复杂</h3><p> 一般将一个Select语句的结果作为子集，然后从该子集中再进行查询，这种一层嵌套语句还是比较常见的，但是根据经验，超过3层嵌套，查询优化器就很容易给出错误的执行计划。因为它被绕晕了，如果人都看晕了，我可以保证数据库也会晕的。</p>
<p>另外执行计划是可以被重用的，越简单的SQL语句被重用的可能性越高。而复杂的SQL语句只要有一个字符发生变化就必须重新解析，然后再把这一大堆垃圾塞在内存里。可想而知，数据库的效率会何等低下。</p>
<p>可以使用with table as语句 ( 目前 oracle、sql server、hive等均支持 with as 用法，但 mysql并不支持！)</p>
<ol>
<li>with table as 可以建立临时表，一次分析，多次使用，同时增加了易读性。</li>
<li>对于复杂查询，使用with table as可以抽取公共查询部分，多次查询时可以提高效率。</li>
</ol>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">--单个语法：</span></span><br><span class="line"><span class="keyword">with</span> tempName <span class="keyword">as</span> (<span class="keyword">select</span> ....)</span><br><span class="line"><span class="keyword">select</span> ...</span><br><span class="line"><span class="comment">--多个语法：</span></span><br><span class="line"><span class="keyword">with</span> tempName1 <span class="keyword">as</span> (<span class="keyword">select</span> ....),</span><br><span class="line">tempName2 <span class="keyword">as</span> (<span class="keyword">select</span> ....),</span><br><span class="line">tempName3 <span class="keyword">as</span> (<span class="keyword">select</span> ....) ...</span><br><span class="line"><span class="keyword">select</span> ...  </span><br><span class="line"></span><br><span class="line"><span class="comment">--例如：</span></span><br><span class="line"><span class="keyword">with</span> citab <span class="keyword">as</span> (<span class="keyword">select</span> ei.customerid,ei.enterprisename,ei.corpid <span class="keyword">from</span> customer_info CI,ent_info ei <span class="keyword">where</span> ci.customerid=EI.Customerid ) </span><br><span class="line"><span class="keyword">Select</span> citab.*,BD.*,BC.* <span class="keyword">from</span>  Business_Duebill BD,Business_Contract BC ,citab <span class="keyword">where</span> bd.relativeserialno2=BC.Serialno </span><br><span class="line"><span class="keyword">and</span> citab.customerid=bc.customerid;</span><br></pre></td></tr></table></figure>

<h3 id="使用”临时表”-暂存中间结果"><a href="#使用”临时表”-暂存中间结果" class="headerlink" title="使用”临时表” 暂存中间结果"></a>使用”临时表” 暂存中间结果</h3><p>临时表就是用来暂时保存临时数据（亦或叫中间数据）的一个数据库对象，它和普通表有些类似，然而又有很大区别。它只能存储在临时表空间，而非用户的表空间。ORACLE临时表是会话或事务级别的，只对当前会话或事务可见。每个会话只能查看和修改自己的数据。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">--会话临时表的语法</span></span><br><span class="line"> <span class="keyword">create</span> <span class="keyword">global</span> <span class="keyword">temporary</span> <span class="keyword">table</span> TMP_TEST</span><br><span class="line"> (</span><br><span class="line">     <span class="keyword">id</span>   <span class="built_in">NUMBER</span>,</span><br><span class="line">      <span class="keyword">name</span> <span class="built_in">VARCHAR2</span>(<span class="number">32</span>)</span><br><span class="line"> )  <span class="keyword">on</span> <span class="keyword">commit</span> <span class="keyword">preserve</span> <span class="keyword">rows</span>;</span><br><span class="line"> 或</span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">GLOBAL</span> <span class="keyword">TEMPORARY</span> <span class="keyword">TABLE</span> TMP_TEST <span class="keyword">ON</span> <span class="keyword">COMMIT</span> <span class="keyword">PRESERVE</span> <span class="keyword">ROWS</span> <span class="keyword">AS</span> <span class="keyword">SELECT</span> * <span class="keyword">FROM</span> <span class="keyword">TEST</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">--即只能在会话级别进行生效。关闭会话即数据丢失。</span></span><br></pre></td></tr></table></figure>

<p><strong>应用场景</strong></p>
<ul>
<li><p>当处理某一批临时数据，需要多次DML操作时（插入、更新等），建议使用临时表.最终将修复数据再进行持久化。</p>
</li>
<li><p>当整个会话过程中涉及多出多表关联相同数据时,那么可以将共性数据进行存储。即前期一次存储。后期多次使用。无需再次提取。</p>
<p>注意事项：</p>
</li>
<li><p>不支持 lob 对象，这也许是设计者基于运行效率的考虑。</p>
<ul>
<li>如果要DROP会话级别临时表，并且其中包含数据时，必须先截断(truncate)其中的数据。否则会报错。</li>
</ul>
</li>
</ul>
<h3 id="索引的建立和使用"><a href="#索引的建立和使用" class="headerlink" title="索引的建立和使用"></a>索引的建立和使用</h3><p><strong>索引的用处</strong></p>
<p>索引是数据库对象之一，用于加快数据的检索，类似于书籍的索引。在数据库中索引可以减少数据库程序查询结果时需要读取的数据量，类似于在书籍中我们利用索引可以不用翻阅整本书即可找到想要的信息。</p>
<p><strong>索引分类</strong></p>
<ul>
<li><p>B树索引</p>
<p>默认索引，保存排序过的索引列和对应的rowid值</p>
<p>列基数（列不重复值的个数）时适合使用B数索引</p>
<p>语法：create index indexName on tableName(column1);</p>
</li>
<li><p>位图索引</p>
<p>创建位图索引时，oracle会扫描整张表，并为索引列的每个取值建立一个位图</p>
<p>对于基数小的列适合位图索引（例如性别、职业等）</p>
<p>语法：create bitmap index index_sex on student(sex);</p>
</li>
<li><p>联合索引</p>
<p>建立联合索引的语法：</p>
<p>create index indexName on tableName(column1,column2,…,columnN)，</p>
<p> 联合索引可以建立多列(列数大于2)的索引,建议列数最多不要越过3列. </p>
</li>
</ul>
<p><strong>索引建立原则总结</strong></p>
<blockquote>
<ul>
<li><p>如果有两个或者以上的索引，其中有一个唯一性索引，而其他是非唯一，这种情况下oracle将使用唯一性索引而完全忽略非唯一性索引</p>
</li>
<li><p>索引应该建立在频繁使用的表列上，并且检索的行数低于总行数的15%。可以考虑建立索引。</p>
</li>
<li><p>限制表的索引个数、索引主要用于加快查询速度，但会降低DML操作。索引越多，DML操作越慢，因此索引规划时需要权衡查询和DML需求。</p>
</li>
<li><p>小表不要建立索引.</p>
</li>
<li><p>对于基数大的列适合建立B树索引，对于基数小的列适合建立位图索引</p>
</li>
<li><p>列中有很多空值，但经常查询该列上非空记录时应该建立索引</p>
</li>
<li><p>经常进行连接查询的列应该创建索引</p>
</li>
<li><p>创建联合索引时要将最常查询的列放在最前面</p>
</li>
<li><p>海量数据表有频繁的更新，这时可以先删除索引，插入数据，再重新建立索引来达到高效的目的。</p>
</li>
</ul>
</blockquote>
<p><strong>索引失效的情况</strong></p>
<blockquote>
<p>Oracle建立索引的目的是为了避免全表扫描，提高查询的效率。</p>
<p>但是有些情况下，即使建立了索引，但是执行写出来的查询还是很慢，然后通过执行计划会发现是索引失效导致的（不走索引，走全表扫描）。所以需要了解一下有哪些情况会导致索引失效。</p>
<p>即查询不走索引的原因：</p>
<ol>
<li><p>使用判断空或非空的条件会导致该索引列失效；</p>
</li>
<li><p>复合索引未用左列字段;</p>
</li>
<li><p>like以%开头;</p>
</li>
<li><p>需要类型转换;</p>
</li>
<li><p>where中索引列有运算;</p>
</li>
<li><p>where中索引列使用了函数;</p>
</li>
<li><p>not in ,not exist.</p>
</li>
<li><p>表没分析.索引失效。</p>
<p>…..</p>
</li>
</ol>
</blockquote>
<h3 id="读懂执行计划"><a href="#读懂执行计划" class="headerlink" title="读懂执行计划"></a>读懂执行计划</h3><p><strong>优化器和成本</strong></p>
<p>在介绍执行计划之前，首先要介绍的就是优化器和成本，优化器是数据库最核心，也是最复杂的一个模块。</p>
<p>选择最优的执行计划。优化器选取，算法决定了执行计划的好坏。</p>
<p>Oracle中优化器是SQL分析和执行的优化工具，它负责生成、制定SQL的执行计划</p>
<p>优化器要是以下两种:</p>
<blockquote>
<p><strong>RBO（Rule-Based Optimization） 基于规则的优化器**</strong></p>
<ul>
<li><p>RBO有严格的使用规则，只要按照这套规则去写SQL语句，无论数据表中的内容怎样，也不会影响到</p>
<p>你的执行计划； </p>
</li>
<li><p>RBO一直沿用至ORACLE 9i，从ORACLE 10g开始，RBO已经彻底被抛弃。</p>
</li>
</ul>
<p><strong>CBO（Cost-Based Optimization） 基于代价的优化器</strong></p>
<ul>
<li><p>CBO是一种比RBO更加合理、可靠的优化器，在ORACLE 10g中完全取代RBO；</p>
</li>
<li><p>CBO通过计算各种可能的执行计划的“代价”，即COST，从中选用COST最低的执行方案作为实际运行方案；</p>
</li>
</ul>
<p>它依赖数据库对象的统计信息，统计信息的准确与否会影响CBO做出最优的选择，也就是对数据“敏感”。</p>
<p>这个就涉及到Oracle收集统计信息。比如Oracle 11g1默认启动了统计信息收集的任务</p>
<p>自动收集的条件：</p>
<ul>
<li>对象的统计信息之前没有收集过。</li>
<li>当对象有超过10%的rows 被修改，此时对象的统计信息也称为stale statistics。</li>
</ul>
</blockquote>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">--查看自动收集任务及状态：</span></span><br><span class="line"><span class="keyword">select</span> client_name,<span class="keyword">status</span> <span class="keyword">from</span> Dba_Autotask_Client <span class="keyword">where</span> client_name=<span class="string">'auto optimizer stats collection'</span>;</span><br><span class="line"><span class="comment">--查看自动收集任务执行时间窗口</span></span><br><span class="line"><span class="keyword">select</span> WINDOW_NAME, WINDOW_NEXT_TIME , WINDOW_ACTIVE,OPTIMIZER_STATS <span class="keyword">from</span> DBA_AUTOTASK_WINDOW_CLIENTS <span class="keyword">order</span> <span class="keyword">by</span> WINDOW_NEXT_TIME ;</span><br></pre></td></tr></table></figure>

<p>手动收集统计信息</p>
<p>一般统计信息用于晚间批量涉及大量数据的变化（插入、更新、删除）。建议手动执行统计信息。</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">--收集表的统计信息</span></span><br><span class="line"><span class="comment">--分析表的所有字段，所有索引，所有索引字段。</span></span><br><span class="line"><span class="keyword">analyze</span> <span class="keyword">table</span> tabname <span class="keyword">compute</span> <span class="keyword">statistics</span>;  </span><br><span class="line"><span class="comment">--分析表的所有字段，所有索引，所有索引字段。效果同上</span></span><br><span class="line"><span class="keyword">analyze</span> <span class="keyword">table</span> tabname <span class="keyword">compute</span> <span class="keyword">statistics</span> <span class="keyword">for</span> <span class="keyword">table</span> <span class="keyword">for</span> <span class="keyword">all</span> <span class="keyword">indexes</span> <span class="keyword">for</span> <span class="keyword">all</span> <span class="keyword">columns</span>;   </span><br><span class="line"><span class="comment">--查询表的统计信息</span></span><br><span class="line"><span class="keyword">select</span> table_name,num_rows,blocks,last_analyzed <span class="keyword">from</span> user_tables <span class="keyword">where</span> table_name=<span class="string">'AUDIT_INFO'</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">-----也可以通过BMS_STATS等包批量分析某个用户或者整个数据库。</span></span><br><span class="line"><span class="comment">--按照用户收集统计信息</span></span><br><span class="line">exec dbms_stats.gather_schema_stats(ownname=&gt;'XXX', options=&gt; 'GATHER AUTO',estimate_percent=&gt; dbms_stats.auto_sample_size,degree=&gt;8,cascade=&gt;true,granularity=&gt;'ALL');  </span><br><span class="line"><span class="comment">--按照表收集统计信息</span></span><br><span class="line">exec  dbms_stats.gather_table_stats(ownname=&gt;'XXX',tabname=&gt;'XXX_TAB',degree=&gt;8,cascade=&gt;true,granularity=&gt;'ALL');</span><br></pre></td></tr></table></figure>

<p>可以根据需要统计的信息 使用存储过程调用或者是编写脚本放入linux定时任务。 每天几点执行。</p>
<p><strong>优化器相关的Hint</strong></p>
<p>在整个SQL优化中，除了按系统默认的优化器来执行，还可以使用提示的方式来干预，能够辅助优化器进行更精准的执行。</p>
<p>主要的Hint包括：</p>
<blockquote>
<ul>
<li><p>ALL_ROWS：它的含义是优化器启用CBO，也就是按照资源消耗量（CPU、I/O等方面）最小来计算执行。</p>
</li>
<li><p>FIRST_ROWS(n) ：它的含义是优化器启用CBO,而且在得到目标SQL的执行计划时会选择那些能够以最快速度响应并返回的前N条记录的执行路径。</p>
<p>注意：如果在Update、delete中使用此hint则会被Oracle忽略。</p>
</li>
<li><p>RULE: 它表示对目标SQL启用RBO，不推荐使用。</p>
</li>
</ul>
</blockquote>
<p><strong>成本</strong></p>
<p>在SQL优化过程中，成本非常重要，Oracle绝大多数都是使用基于成本的优化器来制定执行计划。</p>
<p>成本(COST)计算公式：</p>
<img src="/Oracle/SQL-Oracle/sqlcb.png" style="zoom:50%;">



<p><strong>什么是执行计划？</strong></p>
<p>执行计划是SQL优化的基础，数据库执行的SQL是按照一定的顺序、步骤执行的，至于采用什么方式访问数据由优化器决定。一旦优化器决定好一个它认为最高效的方式，后续一系列的方式顺序、步骤就是执行计划。</p>
<p><strong>执行计划的获取</strong></p>
<p>方式一：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">explain</span> plan <span class="keyword">for</span>  <span class="keyword">select</span> XXX <span class="keyword">from</span> XXX;</span><br><span class="line"><span class="keyword">select</span> * <span class="keyword">from</span> <span class="keyword">table</span>(dbms_xplan.display()); </span><br><span class="line"><span class="comment">--注意只能执行DML语句，不能执行DDL。查看完毕后需要提交或回滚事务</span></span><br><span class="line"><span class="comment">--使用PLSQL Developer连接工具中的F5</span></span><br></pre></td></tr></table></figure>

<p>方式二：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">--跟踪信息记录，最常用的方式，在命令行窗口执行</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 显示执行结果、执行计划、统计信息</span></span><br><span class="line"><span class="keyword">set</span> autotrace <span class="keyword">on</span> <span class="keyword">exp</span> <span class="keyword">statistics</span> ;</span><br><span class="line"><span class="keyword">select</span> * <span class="keyword">from</span> table_name <span class="keyword">where</span> xxx;</span><br><span class="line"><span class="comment">--显示执行计划、统计信息</span></span><br><span class="line"><span class="keyword">set</span> autotrace <span class="keyword">trace</span> <span class="keyword">exp</span> <span class="keyword">statistics</span> ;</span><br><span class="line"><span class="keyword">select</span> * <span class="keyword">from</span> table_name <span class="keyword">where</span> xxx;</span><br><span class="line"><span class="comment">--只显示执行计划</span></span><br><span class="line"><span class="keyword">set</span> autotrace <span class="keyword">trace</span> <span class="keyword">exp</span> ;</span><br><span class="line"><span class="keyword">select</span> * <span class="keyword">from</span> table_name <span class="keyword">where</span> xxx;</span><br><span class="line"></span><br><span class="line"><span class="comment">--补充在执行SQL执行，可显示SQL执行时间</span></span><br><span class="line"><span class="keyword">set</span> timing <span class="keyword">on</span>;</span><br></pre></td></tr></table></figure>

<p><strong>执行计划的简单解读</strong></p>
<ul>
<li><p><strong>执行计划查看顺序</strong></p>
<p>执行计划的查看规则：（从上往下，从右往左）</p>
<p>先从开头一直连续往右看，直到看到右边并列的地方；对于不并列的，靠右的先执行；如果看到并列，从上往下看，对于并列的部分，靠上的先执行。</p>
<p><code>遵循最上最右先执行的原则</code></p>
</li>
<li><p><strong>执行计划字段的解释</strong></p>
<blockquote>
<p><strong>ID</strong>: 一个序号，但不是执行的先后顺序。执行的先后根据缩进来判断。</p>
<p><strong>Operation</strong>： 当前操作的内容。</p>
<p><strong>Rows</strong>： 当前操作的Cardinality，Oracle估计当前操作的返回结果集。</p>
<p><strong>Cost（CPU）：</strong>Oracle 计算出来的一个数值（代价），用于说明SQL执行的代价。</p>
<p><strong>Time</strong>：Oracle 估计当前操作的时间。</p>
</blockquote>
</li>
<li><p><strong>访问路径</strong></p>
<p>访问路径这个步骤是确定以什么方式访问数据库的。</p>
<blockquote>
<p>常见的分类：</p>
<ul>
<li><p>表相关的访问路径：</p>
<p>TABLE ACCESS BY …  即描述的是该动作执行时表访问</p>
<ul>
<li><p>TABLE ACCESS FULL（全表扫描）</p>
<p>Oracle会读取表中所有的行，并检查每一行是否满足SQL语句中的 Where 限制条件；全表扫描时可以使用多块读（即一次I/O读取多块数据块）操作，提升吞吐量；<br>使用建议：数据量太大的表不建议使用全表扫描，除非本身需要取出的数据较多，占到表数据总量的 5% ~ 10% 或以上</p>
</li>
<li><p>TABLE ACCESS BY ROWID（通过ROWID的表存取）</p>
<p>Oracle中存取单行数据最快的方法.</p>
</li>
<li><p>TABLE ACCESS BY INDEX SCAN（索引扫描）</p>
<p>在索引块中，既存储每个索引的键值，也存储具有该键值的行的ROWID。</p>
<p>所以索引扫描其实分为两步：<br>1.扫描索引得到对应的ROWID<br>2.通过ROWID定位到具体的行读取数据</p>
</li>
</ul>
</li>
<li><p>索引相关的访问路径</p>
<p>INDEX….即索引的访问路径</p>
<p>索引扫描又分五种：</p>
<ul>
<li><p>INDEX UNIQUE SCAN（索引唯一扫描）</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">针对唯一性索引（UNIQUE INDEX）的扫描，每次至多只返回一条记录； </span><br><span class="line">表中某字段存在 UNIQUE、PRIMARY KEY 约束时</span><br></pre></td></tr></table></figure>
</li>
<li><p>INDEX RANGE SCAN（索引范围扫描）</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">使用一个索引存取多行数据；</span><br><span class="line">发生索引范围扫描的三种情况：</span><br><span class="line">a、在唯一索引列上使用了范围操作符（如：&gt;   &lt;   &lt;&gt;   &gt;=   &lt;=  	        between）</span><br><span class="line">b、在组合索引上，只使用部分列进行查询（查询时必须包含前导列，否则会走全表    扫描）</span><br><span class="line">c、对非唯一索引列上进行的任何查询。</span><br></pre></td></tr></table></figure>
</li>
<li><p>INDEX FULL SCAN（索引全扫描）</p>
<p>​    进行全索引扫描时，查询出的数据都必须从索引中可以直接得到（注意全索引扫描只有在CBO模式下才有效）</p>
</li>
<li><p>INDEX FAST FULL SCAN（索引快速扫描）</p>
<p>扫描索引中的所有的数据块，与 INDEX FULL SCAN 类似，但是一个显著的区别是它不对查询出的数据进行排序（即数据不是以排序顺序被返回）</p>
</li>
<li><p>INDEX SKIP SCAN（索引跳跃扫描）</p>
<p>前提条件：表有一个复合索引，且在查询时有除了前导列（索引中第一列）外的其他列作为条件，并且优化器模式为CBO时.</p>
<p>当Oracle发现前导列的唯一值个数很少时，会将每个唯一值都作为常规扫描的入口，在此基础上做一次查找，最后合并这些查询；</p>
</li>
</ul>
</li>
<li><p>表关联关系的访问路径</p>
<p>NESTED LOOPS … 描述的是表连接方式</p>
<ul>
<li><p>SORT MERGE JOIN（排序-合并连接）</p>
<p>​    适用的连接方式：&lt;  &lt;= &gt; &gt;= 等。分别会对各表排序，然后合并汇总。</p>
<p>​    首先对两个表按照关联的字段进行排序，分别从两个表中取出一行数据进行匹配，如果合适放入结果集；不匹配将较小的那行丢掉继续匹配另一个表的下一行，依次处理直到将两表的数据取完。merge join的很大一部分开销花在排序上，也是同等条件下差于hash join的一个主要原因。</p>
</li>
<li><p>NESTED LOOPS（嵌套循环）</p>
<p>嵌套循环是比较通用的连接方式，每扫描外表的一行数据都要在内表中查找与之相匹配的行。一般来讲会通过索引来提升性能。</p>
<p><strong>嵌套循环的表有驱动顺序，注意选择合适的驱动表。From最后一张表为驱动表</strong></p>
<p>嵌套循环连接有一个其他连接方式没有的好处是：<strong>可以先返回已经连接的行</strong>，而不必等所有的连接操作处理完才返回数据，这样可以实现快速响应。</p>
<p>通常情况下，优化器在选择执行计划时，不会考虑表在FROM语句中出现的顺序。优化器依次根据下面的规则来作出选择</p>
<p>优化器选择执行计划使得内部表为全表扫描的NESTED LOOPS连接尽可能的少；</p>
<p>如果采用上面的条件出现了平局的情况，则优化器选择尽可能少出现SORT MERGE操作的执行计划；</p>
<p>如果仍然出现平局的情况，则优化器将选择表访问路径中排名最高的表作为驱动表；</p>
<p>如果这时仍然是平局，则优化器会把FROM语句中最后出现的表最为驱动表。</p>
</li>
<li><p>HASH JOIN（哈希连接）</p>
<p>hash-join就算讲两表中的小表（称S）作为hash表，然后去扫描另一个表(称M)的每一行数据，用得出来的行数据根据连接条件去映射建立的hash表，hash表是放在内存中的，这样可以很快的得到对应的S表与M表相匹配的行。</p>
</li>
<li><p>CARTESIAN PRODUCT（笛卡尔积）</p>
<p>通常由编写代码疏漏造成。</p>
</li>
</ul>
<p>注：　　</p>
<ul>
<li>对于结果集很大的情况，merge-join需要对其排序效率并不会很高，而nested loop join是一种嵌套循环的查询方式无疑更不适合大数据集的连接，而hash-join正是为处理这种棘手的查询方式而生，尤其是对于一个大表和一个小表的情况，基本上只需要将大小表扫描一遍就可以得出最终的结果集。</li>
</ul>
</li>
<li><p>不过hash-join只适用于等值连接，对于&gt;, &lt;, &lt;=, &gt;=这样的查询连接还是需要nested loop这种通用的连接算法来处理。如果连接key本来就是有序的或者需要排序，那么可能用merge-join的代价会比hash-join更小，此时merge-join会更有优势。</p>
<ul>
<li>Oracle一次只能连接两个表。不管查询中有多少个表，Oracle在连接中一次仅能操作两张表</li>
</ul>
</li>
</ul>
</blockquote>
<p><strong>统计信息</strong></p>
<table>
<thead>
<tr>
<th>Statistics</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>recursive calls</td>
<td>产生的递归sql调用的条数。</td>
</tr>
<tr>
<td>Db block gets:</td>
<td>从buffer cache中读取的block的数量</td>
</tr>
<tr>
<td>consistent gets</td>
<td>从buffer cache中读取的undo数据的block的数量</td>
</tr>
<tr>
<td>physical reads</td>
<td>从磁盘读取的block的数量</td>
</tr>
<tr>
<td>redo size</td>
<td>DML生成的redo的大小</td>
</tr>
<tr>
<td>bytes sent via SQL*Net to client</td>
<td>数据库服务器通过SQL*Net向查询客户端发送的查询结果字节数</td>
</tr>
<tr>
<td>bytes received via SQL*Net from client</td>
<td>通过SQL*Net接受的来自客户端的数据字节数</td>
</tr>
<tr>
<td>SQL*Net roundtrips to/from client</td>
<td>服务器和客户端来回往返通信的Oracle Net messages条数</td>
</tr>
<tr>
<td>sorts (memory)</td>
<td>在内存执行的排序量</td>
</tr>
<tr>
<td>sorts (disk)</td>
<td>在磁盘上执行的排序量</td>
</tr>
<tr>
<td>rows processed</td>
<td>处理的数据的行数</td>
</tr>
</tbody></table>
</li>
</ul>
<p>使用执行计划进行SQL调优</p>
<ol>
<li><p>查看总COST，获得资源耗费的总体印象 </p>
<p>一般而言，执行计划第一行所对应的COST(即成本耗费)值，反应了运行这段SQL的总体估计成本，单看这个总成本没有实际意义，但可以拿它与相同逻辑不同执行计划的SQL的总体COST进行比较，通常COST低的执行计划要好一些。</p>
</li>
<li><p>按照从左至右，从上至下的方法，了解执行计划的执行步骤 </p>
</li>
<li><p>分析表的访问方式 </p>
</li>
<li><p>分析表的连接方式和连接顺序 </p>
</li>
</ol>
<h3 id="加快SQL的执行速度"><a href="#加快SQL的执行速度" class="headerlink" title="加快SQL的执行速度"></a>加快SQL的执行速度</h3><p><strong>Oracle Hint</strong></p>
<p>基于代价的优化器是很聪明的，在绝大多数情况下它会选择正确的优化器,但有时候也会选择较差的执行计划，使某个语句的执行变得奇慢无比。此时就需要人为干预。告诉优化器应该怎样执行。</p>
<p>当遇到SQL执行计划不好的情况，应优先考虑统计信息等问题，而不是直接加Hint了事。如果统计信息无误，应该考虑物理结构是否合理，即没有合适的索引。只有在最后仍然不能SQL按优化的执行计划执行时，才考虑Hint。</p>
<p>用法：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">INSERT</span>|<span class="keyword">SELECT</span>|<span class="keyword">UPDATE</span>|<span class="keyword">DELETE</span> <span class="comment">/*+ hint  */</span>  ....</span><br><span class="line"><span class="comment">--"+"号表示该注释是一个提示，该加号必须立即跟在"/*"的后面，中间不能有空格。</span></span><br><span class="line"><span class="comment">--hint是下面介绍的具体提示之一，如果包含多个提示，则每个提示之间需要用一个或多个空格隔开。</span></span><br></pre></td></tr></table></figure>

<p>常用Hint:</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*+ parallel(table_name n) */</span></span><br><span class="line"></span><br><span class="line">在sql中指定执行的并行度，这个值将会覆盖自身的并行度和优化器相关的hint</span><br><span class="line"><span class="comment">/*+ ALL_ROWS */</span> 表明对语句块选择基于开销的优化方法,并获得最佳吞吐量,使资源消耗最小化.</span><br><span class="line"><span class="comment">/*+ FIRST_ROWS(n) */</span> 表明对语句块选择基于开销的优化方法,并获得最佳响应时间,使资源消耗最小化.</span><br><span class="line"><span class="comment">/*+ RULE*/</span> 表明对语句块选择基于规则的优化方法.</span><br><span class="line"> 和访问路径相关的hint </span><br><span class="line"><span class="comment">/*+ FULL(TABLE)*/</span> 表明对表选择全局扫描的方法.</span><br><span class="line"><span class="comment">/*+ INDEX(TABLE INDEX_NAME) */</span> 表明对表选择索引的扫描方法.</span><br><span class="line"><span class="comment">/*+ INDEX_ASC(TABLE INDEX_NAME)*/</span> 表明对表选择索引升序的扫描方法.</span><br><span class="line">....</span><br><span class="line">和表相关的所有hint</span><br><span class="line"><span class="comment">/*+ leading(TABLE) */</span>  指定哪个表为驱动表</span><br><span class="line"><span class="comment">/*+ ordered */</span>    指定按照from后面的顺序来选择谁做驱动表</span><br><span class="line"><span class="comment">/*+ use_hash(t,t1) */</span>   表明采用hash方式连接</span><br><span class="line"><span class="comment">/*+ use_nl(t,t1) */</span>   表明采用nested loop方式连接</span><br><span class="line"><span class="comment">/*+ use_merge(t,t1) */</span>  表明采用<span class="keyword">merge</span>方式连接</span><br><span class="line">其他hint</span><br><span class="line"><span class="comment">/*+ parallel(table_name n) */</span> 在<span class="keyword">sql</span>中指定执行的并行度，这个值将会覆盖自身的并行度</span><br><span class="line"><span class="comment">/*+ append */</span>以直接加载的方式将数据加载入库</span><br><span class="line"></span><br><span class="line"><span class="comment">---案例</span></span><br><span class="line"><span class="comment">--使用FIRST_ROWS(n)临时解决查询特别慢的SQL</span></span><br><span class="line"><span class="keyword">select</span><span class="comment">/*+ FIRST_ROWS(5) */</span> * <span class="keyword">from</span> table_xx ;</span><br><span class="line"><span class="comment">--强制走索引</span></span><br><span class="line"><span class="keyword">Select</span>   <span class="comment">/*+ index(tt  IDX_tt_Serialno) */</span>   * <span class="keyword">from</span>  tablename tt <span class="keyword">order</span> <span class="keyword">by</span> serialno;</span><br><span class="line"><span class="comment">--并行</span></span><br><span class="line"><span class="keyword">insert</span> <span class="comment">/*+ parallel(tt 4) */</span> <span class="keyword">into</span> audit_info_temp2 tt  <span class="keyword">Select</span> * <span class="keyword">from</span> audit_info;</span><br><span class="line"><span class="comment">/*+parallel(t,10) (b,10)*/</span> <span class="comment">--多表并行</span></span><br></pre></td></tr></table></figure>

<p><strong>oracle减少redo size的方法：</strong></p>
<blockquote>
<p>oralce日志模式默认情况是logging，就是会记录到redo日志中，force logging是强制记录日志，nologging是尽量减少日志。FORCE LOGGING可以在数据库级别、表空间级别进行设定、而LOGGING与NOLOGGING可以在表级别设定。<br>ORACLE数据库会对产生改变的操作DML记录REDO，比如DDL语句、DML语句，这些操作首先会放在redo buffer中，然后由LGER进程根据触发条件写到联机日志文件，如果数据库开启归档的话，还要在日志切换的时候归档。<br>对于我们来说，最好的调优方式就是不产生REDO或者尽量少的产生REDO。<br>设置NOLOGGING模式<br>此模式不是不记录日志，而是最小化日志产生的数量，通常在下列情况下使用NOLOGGING</p>
<p>/<em>+APPEND</em>/的作用是在表的高水位上分配空间,不再使用表的extent中的空余空间<br>append 属于direct insert, 不去寻找 freelist 中的free block , 直接在table HWM 上面加入数据。</p>
<p>注：归档日志就少了，可能不能用于介质恢复了</p>
</blockquote>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">--nologging模式通常和append联合使用。</span></span><br><span class="line">非归档模式下：</span><br><span class="line"><span class="keyword">insert</span> <span class="comment">/*+ append nologging */</span> <span class="keyword">into</span> audit_info_temp1 <span class="keyword">Select</span> * <span class="keyword">from</span> audit_info;</span><br><span class="line">归档模式下：</span><br><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span> XXX nologging; </span><br><span class="line"><span class="keyword">insert</span> <span class="comment">/*+ append nologging */</span> <span class="keyword">into</span> table1 <span class="keyword">select</span> * <span class="keyword">from</span> table2;</span><br><span class="line"><span class="comment">--查询redo日志产生的大小</span></span><br><span class="line"><span class="keyword">select</span> <span class="keyword">name</span>,<span class="keyword">value</span>,<span class="keyword">class</span> <span class="keyword">from</span> v$sysstat <span class="keyword">where</span> <span class="keyword">name</span>=<span class="string">'redo size'</span>;</span><br></pre></td></tr></table></figure>

<p>Oracle并行</p>
<blockquote>
<p>并行处理的机制实际上就是把一个要扫描的数据集分成很多小数据集，Oracle会启动几个并行服务进程同时处理这些小数据集，最后将这些结果汇总，作为最终的处理结果返回给用户。<br>使用并行方式，不论是创建表，修改表，创建索引，重建索引，他们的机制都是一样的，那就是Oracle 给每个并行服务进程分配一块空间，每个进程在自己的空间里处理数据，最后将处理完毕的数据汇总，完成SQL的操作。</p>
</blockquote>
<p><strong>并行查询</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">--查询当前会话是否开启并行查询  并行查询是默认开启的;</span></span><br><span class="line"><span class="keyword">Select</span> PQ_STATUS <span class="keyword">from</span> v$<span class="keyword">session</span> <span class="keyword">where</span> <span class="keyword">sid</span>=sys_context(<span class="string">'userenv'</span>,<span class="string">'sid'</span>);</span><br><span class="line"><span class="comment">--开启并行查询</span></span><br><span class="line"><span class="keyword">Alter</span> <span class="keyword">session</span> <span class="keyword">enable</span> <span class="keyword">parallel</span> <span class="keyword">query</span>;</span><br><span class="line"><span class="comment">--设置表级的并行数量  一般不建议此方式</span></span><br><span class="line"><span class="keyword">Alter</span> <span class="keyword">table</span> tab1 <span class="keyword">parallel</span> n;<span class="comment">-- 默认为1  不指定为DEFAULT</span></span><br><span class="line"><span class="comment">--Hint方式  建议使用</span></span><br><span class="line"><span class="keyword">Select</span> <span class="comment">/*+parallel(tab n)*/</span> <span class="keyword">from</span> tab;</span><br><span class="line"><span class="keyword">Select</span> <span class="comment">/*+parallel(tab,n)*/</span> <span class="keyword">from</span> tab;</span><br></pre></td></tr></table></figure>

<p><strong>并行DML</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">--查询当前会话是否开启并行DML 并行DML默认是关闭 </span></span><br><span class="line"><span class="keyword">Select</span> PDML_STATUS <span class="keyword">from</span> v$<span class="keyword">session</span> <span class="keyword">where</span> <span class="keyword">sid</span>=sys_context(<span class="string">'userenv'</span>,<span class="string">'sid'</span>);</span><br><span class="line"><span class="comment">--开启和关闭会话并行DML</span></span><br><span class="line"><span class="keyword">alter</span> <span class="keyword">session</span> <span class="keyword">enable</span> <span class="keyword">parallel</span> dml;<span class="comment">--开启</span></span><br><span class="line"><span class="keyword">alter</span> <span class="keyword">session</span> <span class="keyword">disable</span> <span class="keyword">parallel</span> dml;<span class="comment">--关闭</span></span><br><span class="line"><span class="comment">--表级并行  不建议</span></span><br><span class="line"><span class="keyword">Alter</span> <span class="keyword">table</span> tab <span class="keyword">parallel</span> n;<span class="comment">-- 默认为1  不指定为DEFAULT</span></span><br><span class="line"><span class="keyword">insert</span> <span class="keyword">into</span> taba <span class="keyword">Select</span> * <span class="keyword">from</span> tabb;</span><br><span class="line"><span class="comment">--HINT方式  建议</span></span><br><span class="line"><span class="keyword">update</span> <span class="comment">/*+parallel(aa 6) */</span> tabname aa  <span class="keyword">set</span> <span class="keyword">column</span>=XXX;</span><br></pre></td></tr></table></figure>

<p>并行DML使用注意事项：</p>
<blockquote>
<ol>
<li><p>不支持触发器。</p>
</li>
<li><p>在提交和回滚之前。 不能对该表进行DML操作。 </p>
<p>目前已论证：</p>
<p>update 并行只进行行级排它锁。可以非行级锁的操作。如insert</p>
<p>insert  并行会对占用表级排它锁。 无法进行任何DML操作</p>
</li>
<li><p>并行查询是默认开启的。 并行DML默认不开启。</p>
</li>
<li><p>9i之前并行要求必须分区。 9i之后解除了限制。</p>
</li>
</ol>
</blockquote>
<p><strong>并行相关视图查询</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">---查看表相关信息</span></span><br><span class="line"><span class="keyword">Select</span>  table_name,tablespace_name,<span class="keyword">logging</span>,num_rows,degree,partitioned ,user_stats ,last_analyzed <span class="keyword">from</span> user_tables;</span><br><span class="line"><span class="comment">--查看并行执行的会话</span></span><br><span class="line"><span class="keyword">select</span> <span class="keyword">distinct</span>  t.sql_text,t.sql_id,s.sid <span class="keyword">from</span> v$<span class="keyword">sql</span> t,v$<span class="keyword">session</span> s <span class="keyword">where</span> t.sql_id=s.sql_id <span class="keyword">and</span> t.sql_text <span class="keyword">like</span> <span class="string">'%张三%'</span>;</span><br><span class="line"><span class="comment">--查询进程池中的并行进程数 </span></span><br><span class="line"><span class="keyword">select</span> * <span class="keyword">from</span> v$px_process;</span><br></pre></td></tr></table></figure>

<p>注意:</p>
<ul>
<li><p>默认并行度<br>单实例 = PARALLEL_THREADS_PER_CPU x CPU_COUNT<br>RAC = PARALLEL_THREADS_PER_CPU x CPU_COUNT x INSTANCE_COUNT</p>
</li>
<li><p>并行的并行度的优先级从高到低为：</p>
<p><strong>Hint-&gt;alter session force parallel-&gt;表，索引上的设定-&gt; 系统参数</strong></p>
</li>
<li><p>Hint是比较”暴力”的一种解决方式，不是很优雅。需要开发人员手工修改代码。</p>
</li>
<li><p>Hint不会去适应新的变化。比如数据结构、数据规模发生了重大变化，但使用Hint的语句是感知变化并产生更优的执行计划。</p>
</li>
<li><p>Hint随着数据库版本的变化，可能会有一些差异、甚至废弃的情况。此时，语句本身是无感知的，必须人工测试并修正。</p>
</li>
</ul>
<h2 id="SQL优化法则"><a href="#SQL优化法则" class="headerlink" title="SQL优化法则"></a>SQL优化法则</h2><p>常见的优化法则。这里所说的优化法则，其实是指可以从那些角度去考虑SQL优化的问题。可以有很多种方式去看待它。</p>
<img src="/Oracle/SQL-Oracle/sqlyh.png" alt="漏斗法则" style="zoom:80%;">

<p>​    这个优化法则归纳为5个层次：</p>
<ol>
<li><p>减少数据访问（减少磁盘访问）</p>
</li>
<li><p>返回更少数据（减少网络传输或磁盘访问）</p>
</li>
<li><p>减少交互次数（减少网络传输）</p>
</li>
<li><p>减少服务器CPU开销（减少CPU及内存开销）</p>
</li>
<li><p>利用更多资源（增加资源）</p>
<p><strong>自低向上</strong></p>
</li>
</ol>
<img src="/Oracle/SQL-Oracle/oracle_yh.png" alt="自低向上" style="zoom:60%;">

<p>关于SQL、Oracle优化需要探索的内容和方式还有很多，本文只是站在程序员开发角度的思路来整理。</p>
<p>希望能够帮助到各位朋友~</p>
<hr>
<p>本文章部分内容参考文献：《SQL优化最佳实践》</p>
<p>本文参考的文章:</p>
<p>​    <a href="https://www.cnblogs.com/zzl-156783663/p/8506488.html" target="_blank" rel="noopener">https://www.cnblogs.com/zzl-156783663/p/8506488.html</a></p>
<p>​    <a href="http://blog.itpub.net/69918724/viewspace-2651106/" target="_blank" rel="noopener">http://blog.itpub.net/69918724/viewspace-2651106/</a></p>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    ysshao
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://ysshao.cn/Oracle/SQL-Oracle/" title="你真的了解“SQL”吗？">https://ysshao.cn/Oracle/SQL-Oracle/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章遵循 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    
<div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">本文结束<i class="fa fa-paw"></i>感谢您的阅读</div>
    
</div>
  
</div>
    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Oracle/" rel="tag"><i class="fa fa-tag"></i> Oracle</a>
          
            <a href="/tags/SQL%E4%BC%98%E5%8C%96/" rel="tag"><i class="fa fa-tag"></i> SQL优化</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/Oracle/Oracle_Tran/" rel="prev" title="Oracle事务&锁">
                Oracle事务&锁 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/allen.jpg"
                alt="ysshao" />
            
              <p class="site-author-name" itemprop="name">ysshao</p>
              <p class="site-description motion-element" itemprop="description"><font size="2" >本站主要涉及日常技术分享<br>欢迎各位指正和交流。</font><br/></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%7C%7C%20archive">
              
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">4</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/allenshao9" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github-alt"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://ysshao.cn/Notes/" target="_blank" title="Notes">
                      
                        <i class="fa fa-fw fa-gg"></i>Notes</a>
                  </span>
                
            </div>
          
          
          


          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#SQL优化思路-Oracle篇"><span class="nav-number">1.</span> <span class="nav-text">SQL优化思路-Oracle篇</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#SQL语句的执行顺序"><span class="nav-number">1.1.</span> <span class="nav-text">SQL语句的执行顺序</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#理解SQL执行原理和过程"><span class="nav-number">1.2.</span> <span class="nav-text">理解SQL执行原理和过程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#如何写出高性能的SQL"><span class="nav-number">1.3.</span> <span class="nav-text">如何写出高性能的SQL</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#减少硬解析"><span class="nav-number">1.3.1.</span> <span class="nav-text">减少硬解析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参数绑定"><span class="nav-number">1.3.2.</span> <span class="nav-text">参数绑定</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#SQL语句不要太复杂"><span class="nav-number">1.3.3.</span> <span class="nav-text">SQL语句不要太复杂</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用”临时表”-暂存中间结果"><span class="nav-number">1.3.4.</span> <span class="nav-text">使用”临时表” 暂存中间结果</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#索引的建立和使用"><span class="nav-number">1.3.5.</span> <span class="nav-text">索引的建立和使用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#读懂执行计划"><span class="nav-number">1.3.6.</span> <span class="nav-text">读懂执行计划</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#加快SQL的执行速度"><span class="nav-number">1.3.7.</span> <span class="nav-text">加快SQL的执行速度</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#SQL优化法则"><span class="nav-number">1.4.</span> <span class="nav-text">SQL优化法则</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
      </br>
		<div style="">
  <canvas id="canvas" style="width:60%;">当前浏览器不支持canvas，请更换浏览器后再试</canvas>
</div>
<script>
(function(){

   var digit=
    [
        [
            [0,0,1,1,1,0,0],
            [0,1,1,0,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,0,1,1,0],
            [0,0,1,1,1,0,0]
        ],//0
        [
            [0,0,0,1,1,0,0],
            [0,1,1,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [1,1,1,1,1,1,1]
        ],//1
        [
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,0,1,1,0,0,0],
            [0,1,1,0,0,0,0],
            [1,1,0,0,0,0,0],
            [1,1,0,0,0,1,1],
            [1,1,1,1,1,1,1]
        ],//2
        [
            [1,1,1,1,1,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,0,0,1,1,0],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//3
        [
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,1,0],
            [0,0,1,1,1,1,0],
            [0,1,1,0,1,1,0],
            [1,1,0,0,1,1,0],
            [1,1,1,1,1,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,0,1,1,0],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,1,1]
        ],//4
        [
            [1,1,1,1,1,1,1],
            [1,1,0,0,0,0,0],
            [1,1,0,0,0,0,0],
            [1,1,1,1,1,1,0],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//5
        [
            [0,0,0,0,1,1,0],
            [0,0,1,1,0,0,0],
            [0,1,1,0,0,0,0],
            [1,1,0,0,0,0,0],
            [1,1,0,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//6
        [
            [1,1,1,1,1,1,1],
            [1,1,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,1,1,0,0,0],
            [0,0,1,1,0,0,0],
            [0,0,1,1,0,0,0],
            [0,0,1,1,0,0,0]
        ],//7
        [
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//8
        [
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,1,1,0,0,0,0]
        ],//9
        [
            [0,0,0,0,0,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,0,0,0,0,0]
        ]//:
    ];

var canvas = document.getElementById('canvas');

if(canvas.getContext){
    var cxt = canvas.getContext('2d');
    //声明canvas的宽高
    var H = 100,W = 700;
    canvas.height = H;
    canvas.width = W;
    cxt.fillStyle = '#f00';
    cxt.fillRect(10,10,50,50);

    //存储时间数据
    var data = [];
    //存储运动的小球
    var balls = [];
    //设置粒子半径
    var R = canvas.height/20-1;
    (function(){
        var temp = /(\d)(\d):(\d)(\d):(\d)(\d)/.exec(new Date());
        //存储时间数字，由十位小时、个位小时、冒号、十位分钟、个位分钟、冒号、十位秒钟、个位秒钟这7个数字组成
        data.push(temp[1],temp[2],10,temp[3],temp[4],10,temp[5],temp[6]);
    })();

    /*生成点阵数字*/
    function renderDigit(index,num){
        for(var i = 0; i < digit[num].length; i++){
            for(var j = 0; j < digit[num][i].length; j++){
                if(digit[num][i][j] == 1){
                    cxt.beginPath();
                    cxt.arc(14*(R+2)*index + j*2*(R+1)+(R+1),i*2*(R+1)+(R+1),R,0,2*Math.PI);
                    cxt.closePath();
                    cxt.fill();
                }
            }
        }
    }

    /*更新时钟*/
    function updateDigitTime(){
        var changeNumArray = [];
        var temp = /(\d)(\d):(\d)(\d):(\d)(\d)/.exec(new Date());
        var NewData = [];
        NewData.push(temp[1],temp[2],10,temp[3],temp[4],10,temp[5],temp[6]);
        for(var i = data.length-1; i >=0 ; i--){
            //时间发生变化
            if(NewData[i] !== data[i]){
                //将变化的数字值和在data数组中的索引存储在changeNumArray数组中
                changeNumArray.push(i+'_'+(Number(data[i])+1)%10);
            }
        }
        //增加小球
        for(var i = 0; i< changeNumArray.length; i++){
            addBalls.apply(this,changeNumArray[i].split('_'));
        }
        data = NewData.concat();
    }

    /*更新小球状态*/
    function updateBalls(){
        for(var i = 0; i < balls.length; i++){
            balls[i].stepY += balls[i].disY;
            balls[i].x += balls[i].stepX;
            balls[i].y += balls[i].stepY;
            if(balls[i].x > W + R || balls[i].y > H + R){
                balls.splice(i,1);
                i--;
            }
        }
    }

    /*增加要运动的小球*/
    function addBalls(index,num){
        var numArray = [1,2,3];
        var colorArray =  ["#3BE","#09C","#A6C","#93C","#9C0","#690","#FB3","#F80","#F44","#C00"];
        for(var i = 0; i < digit[num].length; i++){
            for(var j = 0; j < digit[num][i].length; j++){
                if(digit[num][i][j] == 1){
                    var ball = {
                        x:14*(R+2)*index + j*2*(R+1)+(R+1),
                        y:i*2*(R+1)+(R+1),
                        stepX:Math.floor(Math.random() * 4 -2),
                        stepY:-2*numArray[Math.floor(Math.random()*numArray.length)],
                        color:colorArray[Math.floor(Math.random()*colorArray.length)],
                        disY:1
                    };
                    balls.push(ball);
                }
            }
        }
    }

    /*渲染*/
    function render(){
        //重置画布宽度，达到清空画布的效果
        canvas.height = 100;
        //渲染时钟
        for(var i = 0; i < data.length; i++){
            renderDigit(i,data[i]);
        }
        //渲染小球
        for(var i = 0; i < balls.length; i++){
            cxt.beginPath();
            cxt.arc(balls[i].x,balls[i].y,R,0,2*Math.PI);
            cxt.fillStyle = balls[i].color;
            cxt.closePath();
            cxt.fill();
        }
    }

    clearInterval(oTimer);
    var oTimer = setInterval(function(){
        //更新时钟
        updateDigitTime();
        //更新小球状态
        updateBalls();
        //渲染
        render();
    },50);
}

})();
</script>
    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
   &nbsp; <i class="fa fa-user"></i>&nbsp;
  </span>
  <span class="author" itemprop="copyrightHolder"> ysshao</span>

  
</div>


  <div class="powered-by">  热爱生活 </div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">分享技术 </div>



<br/>
        
        <span id="busuanzi_container_site_pv">
                本站总访问量<span id="busuanzi_value_site_pv"></span> 次
        </span>
        <span class="post-meta-divider">|</span>
        <span id="busuanzi_container_site_uv" style='display:none'>
                本站访客数<span id="busuanzi_value_site_uv"></span>人
        </span>
        <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  









  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  

    
      <script id="dsq-count-scr" src="https://.disqus.com/count.js" async></script>
    

    

  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('-1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("URBmXUQ1icUgpq16QemUL2AC-gzGzoHsz", "Yon3WfLkAnaC3KuHxJlWt8NL");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "default";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
  </script>

  

  

  

  

</body>
</html>
